// 微信自动回复功能

function onRequest(request, response, modules) {
    var token = "weixin";         //这里的值必须与在微信公众号后台填入的token值一致
    var crypto = modules.oCrypto; //使用加解密模块
    var httptype = modules.oHttptype;　//获取调用云端逻辑的是post或者get方式
    var xml2js = modules.oXml2js;　//实现xml和js格式之间的相互转换
    var db = modules.oData;         //数据库对象
    if ("get" == httptype) {
        　//是get方法,则是微信验证回调的url是否有效
          var oriStr = [token, request.query.timestamp, request.query.nonce].sort().join('')
          var code = crypto.createHash('sha1').update(oriStr).digest('hex');
          if (code == request.query.signature) {　//验证通过，输出
              response.end(request.query.echostr);
          } else {
              response.end("Unauthorized");
          }
    } else {
           //是post,接收定阅者发送过来的消息后返回，把反馈意见存储表“message”中。
            db.insert({
              "table":"message",             //表名
              "data":{"userId":request.body.xml.FromUserName,"content":request.body.xml.Content}
            },function(err,data){
              //构造公众号后台所需要的xml格式，并返回给公众号后台
               var result = {
                    xml: {
                      ToUserName: request.body.xml.FromUserName,
                      FromUserName: request.body.xml.ToUserName ,
                      CreateTime: new Date().getTime(),
                      MsgType: 'text',
                      Content: '圣痕「' + request.body.xml.Content + '」已收到。'
                    }
                }
                var builder = new xml2js.Builder();
                var xml = builder.buildObject(result); //利用模块xml2js，把json对象转换为一个xml文本
                response.set('Content-Type', 'text/xml'); //设置返回的http header
                response.end(xml);
            });



    }
}




// 微信生成签名
function onRequest(request, response, modules) {
    var http = modules.oHttp;
    var crypto = modules.oCrypto;
    var db = modules.oData;

    var nowtime = new Date().getTime();
    var datalist = ['noncestr','jsapi_ticket','timestamp','url'];

    var data = {};
        data.noncestr = 'Wm3WZYTPz0wzc2cnW';
        data.url = request.query.url;

    db.findOne({
      "table":"ticket",
      "objectId":"uG2F111n"
    },function(err,edata){
      var dataObject= JSON.parse(edata);
      data.timestamp = dataObject.last_time;
      data.jsapi_ticket = dataObject.last_ticket;
      mCache();
    });

    function mCache() {
      if(data.timestamp && nowtime <= data.timestamp + 7100*1000){
        setSignature();
      }else{
        data.timestamp = nowtime;
        oloneticket();
      }
    }

    // 获取ticket
    function oloneticket() {
      // 获取access_token
      http('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx07f1a296ba0edc13&secret=4bdc21cfd02dc47a4b6db52e48f13561', function (error, res, body) {
        if (!error && res.statusCode == 200) {
          getticket(JSON.parse(body).access_token);
        }
      });
      // 获取ticket
      function getticket(ticket){
        http('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+ticket+'&type=jsapi', function (error, res, body) {
          if (!error && res.statusCode == 200) {
            data.jsapi_ticket = JSON.parse(body).ticket;
            db.update({
              "table":"ticket",
              "objectId":"uG2F111n",
              "data":{
                "last_time": data.timestamp,
                "last_ticket": data.jsapi_ticket
              }
            },function(err,data){
              setSignature();
            });
          }
        });
      }
    }

    // 生成setSignature
    function setSignature(){
        var sig = [];
        datalist.sort().forEach(function(ele){
            sig.push(ele+'='+data[ele])
        });
        var sigstr = sig.join('&');

        var sha1 = crypto.createHash('sha1');
            sha1.update(sigstr);
        var signature = sha1.digest('hex');

        setreq(signature);
    }

    // 返回数据
    function setreq(sig){
        var req = {};
        req.timestamp = data.timestamp;
        req.nonceStr = data.noncestr;
        req.signature = sig;

        response.send(request.query.callback+"("+JSON.stringify(req)+")");
    }

}
